<template>
  <!-- 搜索区域 -->
  <ContentWrap>
    <ElForm class="-mb-15px" :inline="true" label-width="68px">
      <el-form-item>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['infra:data-source-config:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
      </el-form-item>
    </ElForm>
  </ContentWrap>

  <!-- 列表区域 -->
  <ContentWrap>
    <el-table v-loading="listLoading" :data="list">
      <el-table-column label="数据源编号" prop="id" width="150" />
      <el-table-column label="数据源名称" prop="name" width="200" />
      <el-table-column label="数据源连接" prop="url" show-overflow-tooltip />
      <el-table-column label="用户名" prop="username" width="200" />
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['infra:data-source-config:update']"
            v-if="scope.row.id > 0"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['infra:data-source-config:delete']"
            v-if="scope.row.id > 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DataSourceConfigForm ref="editFormRef" @success="getList" />
</template>

<script setup lang="ts">
import * as DataSourceConfigApi from '@/api/infra/dataSourceConfig'
import DataSourceConfigForm from './DataSourceConfigForm.vue'

defineOptions({ name: 'InfraDataSourceConfig' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const listLoading = ref(false)
const list = ref([]) // 列表数据

const getList = async () => {
  listLoading.value = true
  try {
    list.value = await DataSourceConfigApi.getDataSourceConfigList()
  } finally {
    listLoading.value = false
  }
}

const handleDelete = async (id: number) => {
  try {
    // 弹出确认框
    await message.delConfirm()
    // 发起删除请求
    await DataSourceConfigApi.deleteDataSourceConfig(id)
    // 成功提示
    message.success(t('common.delSuccess'))
    // 刷新列表(页码不变)
    await getList()
  } catch {}
}

const editFormRef = ref<InstanceType<typeof DataSourceConfigForm>>()
const openForm = (type: string, id?: number) => {
  editFormRef.value?.open(type, id)
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss"></style>
